<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/4/24
 * Time: 8:54
 */

namespace app\admin\model;

use app\first\model\Notice;
use think\Db;

class SystemMessage extends Base {
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $field
     * @param bool $out
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where = [], $order = '', $limit = 10, $field = '', $out = false){
        $list = $this
            ->field($field,$out)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $page = $list->currentPage();
        $total = $list->total();
        foreach ($list as $k => $v){
            $list[$k]['sort_asc'] = $k + 1 + ($page-1) * $limit;
            $list[$k]['sort_desc'] = $total - ($page-1) * $limit - $k;
        }
        return $list;
    }

    public function getOneById($id = 0, $field = 'update_time'){
        $info = $this->field($field,true)->find($id);
        return $info;
    }

    /**
     * @param string|null $title
     * @param string|null $content
     * @param int|null $type 1类目 2优惠 3资讯
     * @param int|null $res_id
     * @param string|null $link
     * @param int|null $order_id
     * @param int|null $send_type 1即时,2定时
     * @param int|null $send_time
     * @param array|null $send_uid
     * @param string|null $user_type
     * @param string|null $out
     * @return bool
     * @throws \Exception
     */
    public function add(string $title=null,string $content=null,int $type=null,int $res_id=null,string $link=null,
                        int $order_id=null,int $send_type=null,int $send_time=null,array $send_uid=null,string $user_type=null,
                        string &$out=null): bool
    {
        $data = [
            'title'=>$title,
            'content'=>$content,
            'type'=>$type,
            'res_id'=>$res_id,
            'link'=>$link,
            'order_id'=>$order_id,
            'send_type'=>$send_type,
            'send_time'=>$send_time,
            'send_uid'=>implode(',',$send_uid),
            'user_type'=>$user_type,
        ];
        $validate = new \app\admin\validate\SystemMessage();
        if(!$validate->check($data)){
            $out = $validate->getError();
            return false;
        }
        Db::startTrans();
        $id = $this->insertGetId($data);
        $result = true;
        if($send_uid && $send_type==1){
            $result = (new Notice())->addNewAll($send_uid,$title,$content,4,$type,$res_id,$link,$id);
        }
        if($id && $result){
            Db::commit();
            return true;
        }else{
            Db::rollback();
            return false;
        }
    }
}